<template>
  <div class="table-all">
    <!-- 搜索区 -->
    <div class="app-container search-box">
      <SearchForm
        :form="searchData.form"
        :options="searchData.options"
        @searchUpdate="search"
        @resetSearchData="resetSearchData"
      ></SearchForm>
    </div>
    <!-- 按钮区 -->
    <div class="app-container table-box">
      <div class="table-main">
        <!-- 表格 -->
        <v-table
          title="路面塌陷事故数据"
          v-if="tableMainHeight>0"
          :table-columns="tableColumns"
          :table-data="tableData"
          :loading="loading"
          :is-index="true"
          ref="table"
          :maxHeight="tableMainHeight">
          <template #topButtonList>
            <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
          </template>
          <template #level="scope">
            {{getDictValue(scope.row.level, levelOptions)}}
          </template>
          <template #status="scope">
            {{getDictValue(scope.row.status, statusOptions)}}
          </template>
          <template #source="scope">
            {{getDictValue(scope.row.source, sourceOptions)}}
          </template>
          <template #operation="scope">
            <a v-if="scope.row.examineResult!=1 && scope.row.examineResult!=2"
               v-hasPermission="['riskAccidentCases:add']" class="table-btn-view table-operation"
               @click="handleEdit(scope.row,false)">{{$t('table.edit')}}</a>
            <a v-hasPermission="['riskAccidentCases:list']" class="table-btn-view table-operation"
               @click="handleDetail(scope.row)">{{$t('table.view')}}</a>
            <a v-hasPermission="['riskAccidentCases:delete']" class="table-btn-delete table-operation"
               @click="singleDelete(scope.row)">{{$t('table.delete')}}</a>
          </template>
        </v-table>
      </div>
      <div class="table-page">
        <!-- 页码 -->
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                    @pagination="search"/>
      </div>
    </div>
    <!-- 详情 -->
    <detailDialog :dialog-visible="detailDialogShow"
                  @success="editSuccess"
                  @close="editClose"
                  :openType="detailOpenType"
                  :id="detailId"
                  :title="detailTitle"
                  :isExamine="isExamine"
    ></detailDialog>
  </div>
</template>

<script>
  import { riskAccidentCasesPage,
    riskAccidentCasesExportDL,
    riskAccidentCasesDelete } from '@/api/risk/accidentCases'
  import SearchForm from '@/components/searchForm/index'
  import ButtonForm from '@/components/ButtonForm/index'
  import VTable from '@/components/VTable/index'
  import Pagination from '@/components/Pagination/index'
  import detailDialog from './detail.vue'
  export default {
    components:{
      VTable,Pagination,detailDialog,SearchForm,ButtonForm
    },
    data(){
      return{
        tableColumns:[
          // {
          //   prop: 'flagCode',
          //   label: '标识码',
          //   minWidth: '150',
          //   slotname: 'flagCode',
          //   options: {}
          // },
          {
            prop: 'name',
            label: '事故案例名称',
            minWidth: '150',
            slotname: 'name',
            options: {}
          },
          {
            prop: 'status',
            label: '事故状态',
            minWidth: '150',
            slotname: 'status',
            options: {}
          },
          {
            prop: 'level',
            label: '事故等级',
            minWidth: '100',
            slotname: 'level',
            options: {}
          },
          {
            prop: 'source',
            label: '事故来源',
            minWidth: '100',
            slotname: 'source',
            options: {}
          },
          {
            prop: 'occurTime',
            label: '发现时间',
            minWidth: '150',
            slotname: 'occurTime',
            options: {}
          },
          {
            prop: 'occurAddr',
            label: '事故地点',
            minWidth: '150',
            slotname: 'occurAddr',
            options: {}
          },
          {
            prop:"createBy",
            label: '创建人',
            minWidth: '150',
            slotname: 'createBy',
            options: {}
          },
          {
            prop:"createTime",
            label: '创建时间',
            minWidth: '150',
            slotname: 'createTime',
            options: {}
          },
          {
            prop: 'operation',
            label: '操作',
            width: '200',
            align: 'center',
            slotname: 'operation',
            overflow: false,
            fixed: 'right'
          }
        ],
        tableData:[],
        selection: [],
        loading:false,
        total:1,
        pageNum:1,
        pageSize:10,
        detailOpenType:"add",
        detailDialogShow:false,
        detailId:"",
        detailTitle:"新增",
        dict:{},
        searchData:{
          form:{
            flagCode:'',
            name:'',
            occurAddr:'',
            status:''
          },
          options:[
            {
              title:"标识码",
              key: "flagCode",
              type: "text",
            },
            {
              title:'事故名称',
              key: "name",
              type: "text",
            },
            {
              title:'事故地址',
              key: "occurAddr",
              type: "text",
            },
            {
              title:'状态',
              key: "status",
              type: "select",
              multiple:false,
              option: {
                data: this.statusOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
          ]
        },
        buttonList:[
          {name:'新增',methods:'handleAdd',type:'primary', hasPremission:["riskAccidentCases:add"]},
          {name: '导出数据', methods: 'handleExport', type:'primary',  hasPremission:["riskAccidentCases:export"]}
        ],
        tableMainHeight: 0,
        // 字典
        statusOptions:[],
        sourceOptions:[],
        typeOptions:[],
        typeOptionsFormat:[],
        levelOptions:[],
        examineResultOptions:[],
        isExamine:false,
      }
    },
    watch: {
      // 字典
      'statusOptions':{
        handler(newVal, oldVal) {
          console.log("newVal=======>",newVal)
          if(newVal){
            this.searchData.options.forEach(t => {
              if (t.key == 'status') {
                t.option.data = newVal
              }
            })
          }
        },
        deep: true,
        immediate: true
      },
      'typeOptionsFormat':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t => {
            if (t.key == 'type') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'levelOptions':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t=>{
            if(t.key=='level'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      }
    },
    methods:{
      getLargeTypeLabel(largeType){
        if(largeType){
          let item  = this.typeOptionsFormat.find(t=>t.value == largeType)
          if(item!=undefined){
            return item.label
          }
          return ''
        }
      },
      getTypeLabel(smallType){
        if(smallType){
          let type = smallType.split(",")
          let item  = this.typeOptionsFormat.find(t=>t.value == type[0])
          if(type.length ==2){
            let type1 = item.children.find(t=> t.value == type[1])
            if(type1!=undefined){
              return type1.label
            }
          }
          if(type.length==3){
            let type1 = item.children.find(t=> t.value == type[1])
            if(type1!=undefined){
              let t =  type1.children.find(x=> x.value == type[2])
              if(t!=undefined){
                return t.label
              }
            }
          }
        }
      },
      getIsSetCase(val){
        if(val==0 || val==1){
          return val ? '是' : '否'
        }
        return ''
      },
      getCheckBoxValue(value,option){
        if(!value){
          return
        }
        let temp = []
        let data = value.split(",")
        data.forEach(t=>{
          let item = option.find(x=> x.value == t)
          if(item != undefined){
            temp.push(item.label)
          }
        })
        return temp.join(",")
      },
      getDictValue(value,option){
        let item = option.find(t=> t.value == value)
        if(item!=undefined){
          return item.label
        }
        return value
      },
      editClose(){
        this.detailDialogShow = false
      },
      editSuccess(){
        this.search()
        this.detailDialogShow = false
      },
      search(){
        this.fetch({
          ...this.searchData.form,
        })
      },
      fetch(params={}){
        params.pageSize = this.pageSize
        params.pageNum = this.pageNum
        // 默认交通设施-道路塌陷事故
        params.type = "3,31"
        console.log("params.===>",params)
        this.loading = true
        riskAccidentCasesPage(params).then(async res=>{
          if(res.code==200){
            this.total = res.data.total
            let rows = res.data.rows
            for(let item of rows){
              item.areaCode = await this.$commonJs.areaCodeToName(item)
            }
            this.tableData = res.data.rows
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final=>{
          this.loading = false
        })
      },
      // 重置搜索条件
      resetSearchData(){
        this.searchData.form = {
          flagCode:'',
          name:'',
          occurAddr:'',
          status:''
        }
      },
      searchAreacodeHandle(arr){
        console.log(arr)
        this.searchData.form.provinceCode=arr[0]
        this.searchData.form.cityCode=arr[1]
        this.searchData.form.countyCode=arr[2]
      },
      // 触发按钮区域按钮方法
      clickButton(methods){
        this[methods]()
      },
      handleDetail(row){
        this.detailId = row.id
        this.detailOpenType = "detail"
        this.detailTitle = "详情"
        this.detailDialogShow = true
        this.isExamine = false
      },
      handleAdd(){
        this.detailOpenType = "add"
        this.detailTitle = "新增"
        this.detailDialogShow = true
        this.isExamine = false
      },
      handleEdit(row,isExamine){
        this.detailId = row.id
        this.detailOpenType = "edit"
        this.detailTitle="编辑"
        this.detailDialogShow = true
        this.isExamine = isExamine
      },
      handleExport(){
        let params = {
          ...this.searchData.form
        }
        params.type = "3,31"
        riskAccidentCasesExportDL(params,`路面塌陷事故数据_${new Date().getTime()}.xlsx`);
      },
      handleImport(){
        console.log("等待处理")
      },
      closeDialog(){
        this.detailDialogShow = false
      },

      singleDelete(row){
        this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.loading = true
          riskAccidentCasesDelete(row.id).then(res=>{
            if(res.code==200){
              this.$message({
                message: this.$t('tips.deleteSuccess'),
                type: 'success'
              })
              this.search()
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          }).finally(final=>{
            this.loading = false
          })
        })
      }
    },
    activated(){
      this.fetch()
    },
    created(){
      // 获取字典值
      this.statusOptions = []
      this.$commonJs.filterDataDict("riskAccidentStatus",this.statusOptions)
      this.sourceOptions = []
      this.$commonJs.filterDataDict("riskAccidentSource",this.sourceOptions)
      this.levelOptions = []
      this.$commonJs.filterDataDict("riskAccidentCasesLevel",this.levelOptions)
      this.examineResultOptions = []
      this.$commonJs.filterDataDict("riskAccidentCasesExamineResult",this.examineResultOptions)
      this.fetch()
    },
    mounted(){
      this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
    }
  }
</script>

<style lang="scss" scoped>
  .table-all {
    display: flex;
    flex-direction: column;
    height: 100%;

    .search-box {
      padding-bottom: 6px;
    }

    .table-box {
      padding-top: 10px;
      flex: 1;
      display: flex;
      flex-direction: column;

      .table-main {
        flex: 1;
        overflow: auto;
      }

      .table-page {
        // padding-top: 10 px;
        // padding-bottom: 10 px;
      }

      ::v-deep .pagination-container {
        text-align: right;
      }

    }
  }
</style>
